package com.srwl.mytx.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.CouponSendRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by max on 16/3/27
 */
public class CouponSendRecordFragment extends BaseFragment {
    private static final String TAG = CouponSendRecordFragment.class.getSimpleName();


    private LinearLayoutManager mLayoutManager;

    private CouponSendRecordAdapter mAdapter;
    private int page = 1;
    private Boolean hasNextPage;
    private ProgressBar progressBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private TextView tvUserName;
    private TextView tvTotalCount;
    private TextView tvTotalMoney;
    private ImageView ivAvatar;
    private List<Coupon> couponList = new ArrayList<>();

    public static CouponSendRecordFragment newInstance() {
        CouponSendRecordFragment fragment = new CouponSendRecordFragment();

        return fragment;
    }


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_send_coupon_record_layout, container, false);

        initViewsAndEvents(view);
        return view;
    }

    protected void initViewsAndEvents(View view) {

        progressBar = view.findViewById(R.id.progress_bar);
        refreshLayout = view.findViewById(R.id.refresh_layout);
        tvUserName = view.findViewById(R.id.tv_username);
        tvTotalCount = view.findViewById(R.id.tv_send_money_count);
        tvTotalMoney = view.findViewById(R.id.tv_send_money_amount);
        ivAvatar = view.findViewById(R.id.iv_avatar);
        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        if (loginUserInfo != null) {
            tvUserName.setText(loginUserInfo.getUsername());
            //Glide.with(getActivity()).load(loginUserInfo.getAvatar()).dontAnimate().into(ivAvatar);
            GlideLoadUtils.glideLoad(getActivity(),loginUserInfo.getAvatar(),ivAvatar);
        }
        RecyclerView recyclerView = view.findViewById(R.id.record_list);
        recyclerView.setVisibility(View.VISIBLE);
        recyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mAdapter = new CouponSendRecordAdapter(getActivity(), couponList);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);
        initRefreshLayout();
        loadData(true);
    }

    private void initRefreshLayout() {
        refreshLayout.setNestedScrollingEnabled(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

                page = 1;
                loadData(false);
            }

            @Override
            public void onLoadingMore() {

                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }


    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }

        Map<String, Object> body = new HashMap();
        body.put("page", page);
        body.put("size", 10);

        RetrofitManager.getInstance().createRequest(CouponService.class)
                .getSendCouponRecord(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取发送红包记录出错：" + response.message());
                            showToast(getString(R.string.system_busy));
                            if (page == 1) {
                                mAdapter.showErrorView();
                            }
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取发送红包记录出错：" + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(getString(R.string.login_expire));
                            }
                            if (page == 1) {
                                mAdapter.showErrorView();
                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "获取发送红包记录完成：" + data.toJSONString());
                        JSONObject pageInfo = data.getJSONObject("pageInfo");
                        List<Coupon> coupons = pageInfo.getJSONArray("list").toJavaList(Coupon.class);
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }
                        //只有第一次获取数据，才会返回 总金额
                        if (page == 1) {
                            Integer totalCount = pageInfo.getInteger("total");
                            Double totalAmount = data.getDouble("totalAmount");
                            setHeaderViews(totalAmount, totalCount);
                        }

                        if (coupons.size() != 0) {
                            couponList.addAll(coupons);
                            mAdapter.showNormalView();
                            page++;
                        } else if (page == 1) {
                            mAdapter.showNoDataView();
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            mAdapter.showErrorView();
                        }
                    }
                });
    }


    private void setHeaderViews(Double totalAmount, Integer totalCount) {
        if (totalAmount == null) {
            totalAmount = 0d;
        }
        if (totalCount == null) {
            totalCount = 0;
        }
        tvTotalMoney.setText(String.format("￥%s", totalAmount));
        tvTotalCount.setText(String.valueOf(totalCount));
    }


}
